import os
import logging
from api import utils, models
from api.serial import mould, sample
from api.serial.detect import detect_sample
from detecter import settings

logger = logging.getLogger('serial.requestHandler')


# 对检测出错的样本进行反馈来更新阈值，不处理负样本标签地误标记, unassigned_file也先不做处理
# by zxy on 20200103
def feedback_to_update_threshold(db_mould, current_mould, sample_id, sample_type):
    logger.info("进行反馈中...")
    good_file, sample_path, rejects_file = current_mould.good_file, \
                                           current_mould.sample_path, current_mould.rejects_file
    try:
        sample_file = models.Sample.objects.get(sample_id=sample_id, mould=db_mould)
    except:
        return utils.R.error('该样本未找到')
    sample_times = sample_file.times
    origin_threshold = db_mould.threshold
    new_threshold = origin_threshold
    sample_file.state = 3  # 已反馈
    difference = float(sample_times) - origin_threshold

    logger.info(str(sample_type))
    logger.info(str(difference))
    # 本该是正样本却检测为负样本，需要加大阈值
    if sample_type == "positive":
        logger.info("flag 0")
        if difference > 0:
            new_threshold = origin_threshold + difference * 0.5
        else:
            new_threshold = origin_threshold
        logger.error(f'{sample_id} 系统将品质正常误判成不良品')
        # mould.CurrentMould.pos_feedback()
        utils.restore_sample(rejects_file, good_file, [sample_id])
        # mould.CurrentMould.pos_feedback()
        db_mould.pos_increment()  # 正样本+1
        db_mould.neg_reduce()  # 负样本-1
        sample_file.label_id = 2

    # 本该是负样本却检测为正样本，需要减小阈值
    elif sample_type == "negative":
        if difference < 0:
            new_threshold = origin_threshold + difference * 1.1
        else:
            new_threshold = origin_threshold
        logger.info(f'{sample_id},不良品误判成品质正常')
        utils.restore_sample(good_file, rejects_file, [sample_id])
        # 网络
        # mould.CurrentMould.neg_feedback()
        db_mould.neg_increment()  # 负样本+1
        db_mould.pos_reduce()  # 正样本-1
        sample_file.label_id = 1
    else:
        return utils.R.error(f'id为{sample_id}的样本不符合负反馈规则，请检查该样本是否需要误判反馈')

    if new_threshold < 3.0:
        new_threshold = 3.0
    db_mould.threshold = new_threshold
    db_mould.save()

    sample_file.save(force_update=True)
    logger.info("flag 1")

    return utils.R.ok()